package com.seven.netty.protocol.server;

import com.seven.netty.protocol.codec.MessageDecoder;
import com.seven.netty.protocol.codec.MessageEncoder;
import com.seven.netty.protocol.handler.ClientHeartBeatHandler;
import com.seven.netty.protocol.handler.LoginReqHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author chendongdong
 * @description TODO
 * @since 2024/3/6 11:47
 */
@Slf4j
public class TcpClient {
    private NioEventLoopGroup workGroup = new NioEventLoopGroup(4);
    private Channel channel;
    private Bootstrap bootstrap;
    private final String host;
    private final Integer port;

    public TcpClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /***
     * 启动客户端
     */
    public void start() {
        try {
            bootstrap = new Bootstrap();
            bootstrap
                .group(workGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel socketChannel) throws Exception {
                        ChannelPipeline p = socketChannel.pipeline();
                        //添加心跳检测的Handler，监听读写空闲，当10秒内没有数据交互，则触发读写空闲事件，发送心跳包
                        p.addLast(new IdleStateHandler(0, 15, 0));
                        p.addLast(new MessageDecoder())
                            .addLast(new MessageEncoder())
                            .addLast(new ClientHeartBeatHandler())
                            .addLast(new LoginReqHandler());
                    }
                });
            //连接服务器
            doConnect();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /***
     * 开始连接
     */
    public void doConnect() {
        if (channel != null && channel.isActive()) {
            return;
        }
        ChannelFuture future = bootstrap.connect(host, port);
        future.addListener((ChannelFutureListener) futureListener -> {
            if (futureListener.isSuccess()) {
                channel = futureListener.channel();
                log.info("Connect to server successfully!");
            } else {
                log.info("Failed to connect to server, try connect after 10s");
                futureListener.channel().eventLoop().schedule(() -> doConnect(), 10, TimeUnit.SECONDS);
            }
        });
    }
}
